package jsonrpc

import (
	"encoding/json"
	"raymond/global"
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

var url string

func SetUrl(uri string) {
	url = uri
}

type eth_request struct {
	Jsonrpc string `json:"jsonrpc"`
	Method  string `json:"method"`
	Params  []any  `json:"params"`
	Id      int    `json:"id"`
}

type eth_response struct {
	Jsonrpc string `json:"jsonrpc"`
	Result  string `json:"result"`
	Error   string `json:"error"`
	Id      int    `json:"id"`
}

func GetBalance(account string) (int64, error) {
	req := eth_request{
		Jsonrpc: "2.0",
		Method:  "eth_getBalance",
		Params:  []any{account, "latest"},
		Id:      1,
	}

	req_bytes, _ := json.Marshal(req)
	resp_bytes, _ := global.HttpPost(url, req_bytes)
	var resp eth_response
	json.Unmarshal(resp_bytes, &resp)

	if len(strings.TrimSpace(resp.Error)) > 0 {
		return 0, errors.New(resp.Error)
	}

	num, _ := strconv.ParseInt(resp.Result, 0, 64)
	return num, nil
}

func BlockNumber() (string, error) {
	req := eth_request{
		Jsonrpc: "2.0",
		Method:  "eth_blockNumber",
		Id:      83,
	}

	req_bytes, _ := json.Marshal(req)
	resp_bytes, _ := global.HttpPost(url, req_bytes)
	var resp eth_response
	json.Unmarshal(resp_bytes, &resp)

	if len(strings.TrimSpace(resp.Error)) > 0 {
		return "", errors.New(resp.Error)
	}

	return resp.Result, nil
}

func GetBlockByNumber(number string) (string, error) {
	req := eth_request{
		Jsonrpc: "2.0",
		Method:  "eth_getBlockByNumber",
		Params:  []any{"latest", true},
		Id:      1,
	}

	req_bytes, _ := json.Marshal(req)
	resp_bytes, _ := global.HttpPost(url, req_bytes)
	var resp eth_response
	json.Unmarshal(resp_bytes, &resp)

	if len(strings.TrimSpace(resp.Error)) > 0 {
		return "", errors.New(resp.Error)
	}

	return resp.Result, nil
}
